import React, { Component } from 'react'
import Header from '../../components/Header'
import { getLocalCity } from '../../utils/localCity'
import API from '../../utils/api'
import './index.scss'

const BMapGL = window.BMapGL

export default class Map extends Component {
  state = {
    houseList: []
  }

  componentDidMount() {
    this.initMap()
  }

  initMap = async () => {
    const { label: localCity, value: CityValue } = await getLocalCity()

    this.map = new BMapGL.Map("container")

    this.map.addEventListener('movestart', () => {
      this.setState({
        houseList: []
      })
    })

    const myGeo = new BMapGL.Geocoder()
    myGeo.getPoint(localCity, async point => {
      if (!point) {
        return null
      }

      this.map.centerAndZoom(point, 11)
      // this.map.enableScrollWheelZoom(true)
      this.map.disableDoubleClickZoom()
      this.map.addControl(new BMapGL.ScaleControl())
      this.map.addControl(new BMapGL.ZoomControl())

      this.renderOverlays(CityValue)
    }, localCity)

  }

  renderOverlays = async (CityValue) => {
    const { data: areaData } = await API.get(`/area/map?id=${CityValue}`)

    const mapZoom = this.map.getZoom()
    let nextZoom = 11, renderType = 'circle'

    if (mapZoom >= 10 && mapZoom < 12) {
      nextZoom = 13
      renderType = 'circle'
    } else if (mapZoom >= 12 && mapZoom < 14) {
      nextZoom = 15
      renderType = 'circle'
    } else {
      renderType = 'rect'
    }

    if (renderType === 'circle') {
      this.renderCircleShape(areaData, nextZoom)
    } else {
      this.renderRectShape(areaData)
    }
  }

  renderCircleShape = (areaData, nextZoom) => {
    areaData.body.forEach(item => {
      const { coord: { latitude, longitude }, count, label, value } = item

      const circlePosition = {
        lng: longitude,
        lat: latitude
      }

      const circle = new BMapGL.Label(`<div class="area-box">
        <div>${label}</div>
        <p>${count}套</p>
      </div>`, {
        offset: { width: -35, height: -35 },
        position: circlePosition
      })

      circle.setStyle({
        border: 0,
        borderRadius: '50%'
      })

      circle.addEventListener('click', () => {
        this.renderOverlays(value)
        this.map.clearOverlays()
        this.map.centerAndZoom(circlePosition, nextZoom)
      })

      this.map.addOverlay(circle)
    })
  }

  renderRectShape = (areaData) => {
    areaData.body.forEach(item => {
      const { coord: { latitude, longitude }, count, label, value } = item

      const circlePosition = {
        lng: longitude,
        lat: latitude
      }

      const rect = new BMapGL.Label(`<div class="rect-box">
        <div>${label}--${count}套</div>
      </div>`, {
        offset: { width: 0, height: 0 },
        position: circlePosition
      })

      rect.setStyle({
        border: 0
      })

      rect.addEventListener('click', (e) => this.getHouseList(value, e))

      this.map.addOverlay(rect)
    })
  }

  getHouseList = async (value, e) => {
    console.log(e)

    const panByX = window.innerWidth / 2 - e.currentTarget.domElement.offsetLeft
    const panByY = (window.innerWidth - 320) / 2 -  e.currentTarget.domElement.offsetTop

    this.map.panBy(panByX - e.currentTarget.domElement.offsetWidth / 2, panByY + e.currentTarget.domElement.offsetHeight)

    const {data} = await API.get(`/houses?cityId=${value}`)

    if(data.status !== 200) {
      return alert(data.description)
    }

    this.setState({ houseList: data.body.list })
  }

  renderHouseList = () => {
    return (
      <div className={["houselist-box", this.state.houseList.length > 0 ? "houselist-box-show" : ""].join(' ')}>
        <div className="houselist-title">房屋列表</div>
        <div className="houselist-list">
          {this.state.houseList.map(item => {
            return (<div className="houselist-item" key={item.houseImg}>
              <div className="houselist-item-left">
                <img src={`http://127.0.0.1:8080${item.houseImg}`} alt="" />
              </div>
              <div className="houselist-item-right">
                <div className="houselist-item-right-title">{item.title}</div>
                <div className="houselist-item-right-desc">{item.desc}</div>
                <div className="houselist-item-right-tags">{item.tags}</div>
                <div className="houselist-item-right-price">{item.price}</div>
              </div>
            </div>)
          })}
        </div>
      </div>
    )
  }

  render() {
    return (
      <div className="map">
        <Header className="map-header" title="地图找房" />

        <div id="container"></div>

        {this.renderHouseList()}
      </div>
    )
  }
}
